<template>
	<div id="uploadVideoFm">

		<video id="video" v-if="tempVideo" controls controlslist="nodownload"   width="300" height="auto" :src="tempVideo">
		</video>


		<img class="videoImg" :src="imgData" />

		<canvas id="videoCavas" :width="canvasList.width" :height="canvasList.height"></canvas>

		<!--主要视频-->

		<div class="videoSuccess flex">

			<div class="video_box flex">

				<div class=""  v-if="tempVideo">
					<video class="videoShow" preload="auto" height="auto" controls controlslist="nodownload"   :src="tempVideo">
					</video>
				</div>

				<div class="" v-if="fatherVideo">
					<video  class="videoShow" height="auto"  preload="auto" controls controlslist="nodownload"  :src="fatherVideo">
					</video>
				</div>

				<div class="" style="width:100px;position:relative;">
					<span v-if="videoStatus == 0" class="iconShow">线上视频</span>
					<span v-if="videoStatus == 1" class="iconShow">本地视频</span>
					<span v-if="videoStatus == 2" class="iconShow">上传成功</span>

					<div class="videoBtn_box">
						<el-button type="primary" v-if="!tempVideo" size="small">选择视频</el-button>
						<el-button type="primary" v-if="tempVideo" size="small">重选视频</el-button>
						<input class="videoBtn" type="file" name="" id="" @change="getFile" value="" ref="upload" />
					</div>
					
					
					<div id="" style="margin: 20px;">
						<el-progress v-if="videoList.isVideoUpload==1" type="circle" :width="80" :percentage="videoList.videoPercent"></el-progress>
					</div>
					
					
					<div class="videoBtn_box" style="margin:10px 20px;">
						<el-button v-if="tempVideo" type="primary" @click="videoSuccess" size="small">确定上传</el-button>
					</div>
					
					

				</div>

			
			</div>

		</div>

	</div>

</template>

<script>
	import requestUrl from '@/util/requestUrl'
	import utils from '@/util/utils'
	export default {

		props: {
			fatherVideo: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				requestUrl: requestUrl,

				fatherShow: 1,

				videoList: {
					video: "",
					image: "",
					isVideoUpload: 0,
				},
				
				videoStatus:0,

				//临时地址
				tempVideo: "",

				canvasShow: 0,
				canvasList: {
					width: 100,
					height: 100
				},

				coverImg: "", //封面图

				uploadImgFile: "",
				imgData: "",

			}
		},
		destory() {

		},
		mounted() {

		},
		methods: {

			//上传前
			beforeVideo: function(res) {
				var type = res.type;
				var endVideo = type.split("/");
				if(endVideo[0] != 'video') {
					this.$message.error("请上传视频");
					return false;
				}

			},

			//视频上传
			videoSuccess: function(uploader) {
				var _this = this;
				var ele = this.$refs.upload;
				var videoFile = ele.files[0];

				if(!videoFile) {
					this.$message.error("请选择视频");
					return false;
				}

				this.videoList.isVideoUpload = 1;
				//封面图
				var img = this.captureImage();
				//视频
				var video = this.submitVideo();

				Promise.all([img, video]).then((result) => {
					_this.$emit('myVideo', result)
				}).catch((error) => {
					this.$message.error("上传失败");
				})

			},

			//获取文件
			getFile: function(res) {
				var ele = this.$refs.upload;
				var videoFile = ele.files[0];
				this.videoStatus = 1;
				//判断是否是视频文件
				var type = videoFile.type;
				var endVideo = type.split("/");
				if(endVideo[0] != 'video') {
					var ele = this.$refs.upload;
					this.$message.error("请上传视频");
					ele.value = ""; //重新初始化了file的html
					return false;
				}
				
				var urls = URL.createObjectURL(videoFile);
				this.tempVideo = urls;
				this.$emit('localVideo',{status:1})
			},

			//上传视频
			submitVideo: function(res) {
				var _this = this;
				var ele = this.$refs.upload;
				var videoFile = ele.files[0];
				this.$emit('localVideo',{status:2})
				let promises = new Promise((resolve, reject) => {
					var form = new FormData();
					//uploader为之前提到的实例
					form.append("video", videoFile);
					_this.$set(_this.videoList, "videoPercent", 0);
					utils.uploadSectionFile(form, function(res) {
						_this.$set(_this.videoList, "video", res.data);
						resolve(res.data)
						_this.videoStatus = 2;
						_this.tempVideo = "";
						_this.$emit('localVideo',{status:3})
					}, function(numbers) {
						_this.$set(_this.videoList, "videoPercent", numbers);
					});

				});

				return promises;
			},

			//截图
			captureImage: function(res) {
				let promises = new Promise((resolve, reject) => {
					var scale = 0.8; //质量比例
					var video = document.getElementById("video");
					var canvas = document.getElementById("videoCavas");
					this.canvasList = {
						width: video.clientWidth,
						height: video.clientHeight,
					};

					this.$nextTick(() => {
						canvas.getContext("2d").drawImage(video, 0, 0, video.clientWidth, video.clientHeight);
						var base64 = canvas.toDataURL("image/jpg");
						this.imgData = base64;

						var blobs = this.base64ToBlob(base64);

						var files = this.dataURLtoFile(base64, 'videoImg.png')
						
						//上传图片
						var form = new FormData(); //uploader为之前提到的实例
						form.append("image", files);
						form.append("type", 1);
						form.append("mch_type", 6);
						var request = new XMLHttpRequest();
						request.open("POST", "https://afe.aapppp.cn/admin/image");
						request.onload = function(e) {
							if(e.currentTarget.status == 200) {
								var data = JSON.parse(request.responseText);
								this.coverImg = data.data;
								resolve(data.data)
							} else {
								reject({
									errormsg: '网络错误,请稍后重试',
									code: -1
								})
							}
						}
						request.send(form);

					})

				});
				return promises;

			},

			//上传视频封面
			uploadImg: function(urls) {
				var _this = this;
				var form = new FormData(); //uploader为之前提到的实例
				form.append("image", urls);
				form.append("type", 1);
				form.append("mch_type", 6);
				var request = new XMLHttpRequest();
				request.open("POST", "https://afe.aapppp.cn/admin/image");
				request.onload = function(e) {
					if(e.currentTarget.status == 200) {
						var data = JSON.parse(request.responseText);
						this.coverImg = data.data;

					}
				}
				request.send(form);
			},

			// base64转flie
			dataURLtoFile: function(dataurl, filename) { //将base64转换为文件，dataurl为base64字符串，filename为文件名（必须带后缀名，如.jpg,.png）
				var arr = dataurl.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while(n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new File([u8arr], filename, {
					type: mime
				});
			},

			// base64转blob
			base64ToBlob: function(base64Data) {
				let arr = base64Data.split(','),
					fileType = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					l = bstr.length,
					u8Arr = new Uint8Array(l);

				while(l--) {
					u8Arr[l] = bstr.charCodeAt(l);
				}
				return new Blob([u8Arr], {
					type: fileType
				});
			},
			// blob转file
			blobToFile: function(newBlob, fileName) {

				newBlob.lastModifiedDate = new Date();
				newBlob.name = fileName;
				return newBlob;
			},

		},
		watch: {
			initText() {

			},
			'videoList.video': function(res) {

				//				let itme = setTimeout((res) => {
				//					this.captureImage()
				//				}, 4000)
			},

			fatherVideo: function(res) {
				this.fatherShow = 0;
				console.log(res, '变化')

			}
		}
	}
</script>

<style lang="less" scoped="scoped">
	#videoCavas {
		position: fixed;
		/*top: 10000px;*/
		opacity: 0;
	}
	
	.videoSuccess {
		display: flex;
	}
	
	.videoImg {
		position: fixed;
		/*top: 10000px;*/
		opacity: 0;
	}
	
	#video {
		position: fixed;
		/*top: 10000px;*/
		opacity: 0;
	}
	
	.video_box {
		position: relative;
	}
	
	.videoShow {
		width: 200px;
	}
	
	.videoBtn_box {
		position: relative;
		margin-left: 20px;
	}
	
	.iconShow {
		color: #0589FD;
		position: absolute;
		top: -40px;
		right: 20px;
		z-index: 1;
		border-bottom: 2px solid #0589FD;
	}
	
	.videoBtn {
		width: 100px;
		height: 35px;
		opacity: 0;
		position: absolute;
		top: 0;
		left: 0;
		border: 1px solid red;
	}
</style>